package io.github.lee.repository.qb.di.http.interceptor

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import okhttp3.Interceptor
import okhttp3.Response

class CookieInterceptor(context: Context) : Interceptor {

    private val cookieStore: CookieStore = CookieStore(context)

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val localCookie = cookieStore.loadCookie(request.url.host)
        val response = if (localCookie.isNullOrEmpty()) {
            chain.proceed(request)
        } else {
            val cookieRequest = request.newBuilder().addHeader("Cookie", localCookie)
                .build()
            chain.proceed(cookieRequest)
        }
        //保存cookie
        val responseCookie = response.headers["set-cookie"]
        if (!responseCookie.isNullOrEmpty()) {
            cookieStore.saveCookie(response.request.url.host, responseCookie)
        }

        return response
    }


}

private class CookieStore(context: Context) {
    private val sp: SharedPreferences
    private val fileName = "${context.packageName}.cookies"

    init {
        sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
    }

    fun saveCookie(host: String, cookie: String?) {
        sp.edit { putString(host, cookie) }
    }

    fun loadCookie(host: String): String? {
        return sp.getString(host, null)
    }

    fun removeCookie(host: String) {
        sp.edit { remove(host) }
    }
}
